package lib

import (
	"database/sql"
	"log"
	"sync"

	_ "github.com/go-sql-driver/mysql"
)

type DB struct {
	conn   *sql.DB
	isOpen bool
}

var ins *DB
var once sync.Once

func GetDb(driverName, dataSourceName string) *DB {
	once.Do(func() {
		ins = &DB{}

		if !ins.isOpen {
			var err error
			ins.conn, err = sql.Open(driverName, dataSourceName)
			if err != nil {
				log.Fatal("mysql连接错误", err)
			}
		}
	})
	return ins
}

func (dbconn *DB) CloseDb() {
	if dbconn.isOpen {
		dbconn.isOpen = false
		dbconn.conn.Close()
	}
}

func (dbconn *DB) Insert(sql string, args ...interface{}) int64 {
	stmt, err := dbconn.conn.Prepare(sql)
	if err != nil {
		log.Fatal("插入数据错误1:", err)
	}
	log.Print(args)
	res, err := stmt.Exec(args...)
	if err != nil {
		log.Fatal("插入数据错误2:", err)
	}
	id, err := res.LastInsertId()
	if err != nil {
		log.Fatal("插入数据错误3:", err)
	}
	if err != nil {
		return 0
	} else {
		return id
	}
}

func (dbconn *DB) Select(sql string, args ...interface{}) *sql.Rows {
	rows, err := dbconn.conn.Query(sql, args...)
	if err != nil {
		log.Fatal(err)
	}
	return rows
}

func (dbconn *DB) SelectOne(sql string, args ...interface{}) *sql.Row {
	row := dbconn.conn.QueryRow(sql, args...)
	return row
}
